package com.saris.primego.service.impl;

import com.saris.primego.common.constant.MessageConstant;
import com.saris.primego.common.constant.StatusConstant;
import com.saris.primego.common.context.BaseContext;
import com.saris.primego.common.exception.DeletionNotAllowedException;
import com.saris.primego.common.exception.EntityNotFoundException;
import com.saris.primego.common.result.PageResult;
import com.saris.primego.dao.CategoryRepository;
import com.saris.primego.dao.DishRepository;
import com.saris.primego.dao.SetmealRepository;
import com.saris.primego.pojo.dto.CategoryDTO;
import com.saris.primego.pojo.dto.CategoryPageQueryDTO;
import com.saris.primego.pojo.entity.Category;
import com.saris.primego.pojo.entity.Dish;
import com.saris.primego.pojo.entity.Setmeal;
import com.saris.primego.service.CategoryService;
import jakarta.persistence.criteria.Predicate;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 分类业务层
 */
@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {
    final ModelMapper modelMapper;
    final CategoryRepository categoryRepository;
    final DishRepository dishRepository;
    final SetmealRepository setmealRepository;

    public CategoryServiceImpl(ModelMapper modelMapper, CategoryRepository categoryRepository, DishRepository dishRepository, SetmealRepository setmealRepository) {
        this.modelMapper = modelMapper;
        this.categoryRepository = categoryRepository;
        this.dishRepository = dishRepository;
        this.setmealRepository = setmealRepository;
    }

    /**
     * 新增分类
     */
    public void addCategory(CategoryDTO categoryDTO) {
        Category category = modelMapper.map(categoryDTO, Category.class);

        //分类状态默认为禁用状态0
        category.setStatus(StatusConstant.DISABLE);

        //设置创建时间、修改时间、创建人、修改人
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        category.setCreateUser(BaseContext.getCurrentId());
        category.setUpdateUser(BaseContext.getCurrentId());

        categoryRepository.save(category);
    }

    /**
     * 分页查询
     */
    public PageResult<Category> pageQuery(CategoryPageQueryDTO categoryPageQueryDTO) {
        int size = categoryPageQueryDTO.getPageSize();
        int page = categoryPageQueryDTO.getPage();
        String name = categoryPageQueryDTO.getName();
        Integer type = categoryPageQueryDTO.getType();

        Pageable pageable = PageRequest.of(page - 1, size, Sort.by("sort")); // 由于pageNumber 从 0 开始，传入的页码需要-1

        // 动态构建查询条件
        Specification<Category> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            // 当 name 不为空时，添加 name 条件
            if (name != null && !name.trim().isEmpty()) {
                predicates.add(cb.like(root.get("name"), "%" + name + "%"));
            }
            // 当 type 不为空时，添加 type 条件
            if (type != null) {
                predicates.add(cb.equal(root.get("type"), type));
            }
            if (predicates.isEmpty()) {
                return cb.conjunction();

            } else {
                return cb.and(predicates.toArray(new Predicate[0]));
            }

        };

        Page<Category> all = categoryRepository.findAll(spec, pageable);
        return new PageResult<>(all.getTotalElements(), all.getContent());
    }

    /**
     * 根据id删除分类
     */
    public void deleteById(Long id) {
        //查询当前分类是否关联了菜品，如果关联了就抛出业务异常
        List<Dish> dishes = dishRepository.findDishesByCategoryId(id);
        if (dishes != null && !dishes.isEmpty()) {
            //当前分类下有菜品，不能删除
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }

        //查询当前分类是否关联了套餐，如果关联了就抛出业务异常
        List<Setmeal> setmeals = setmealRepository.findSetmealsByCategoryId(id);
        if (setmeals != null && !setmeals.isEmpty()) {
            //当前分类下有菜品，不能删除
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }

        //删除分类数据
        categoryRepository.deleteById(id);
    }

    /**
     * 修改分类
     */
    @Transactional
    public void update(CategoryDTO categoryDTO) {
        // 1. 查询现有实体
        Category category = categoryRepository.findById(categoryDTO.getId())
                .orElseThrow(() -> new EntityNotFoundException(MessageConstant.CATEGORY_NOT_FOUND));

        // 2. 将 DTO 的非空字段映射到实体（跳过 null 值）
        modelMapper.map(categoryDTO, category);
        //设置修改时间、修改人
        category.setUpdateTime(LocalDateTime.now());
        category.setUpdateUser(BaseContext.getCurrentId());

    }

    /**
     * 启用、禁用分类
     */
    public void startOrStop(Integer status, Long id) {
        Optional<Category> optionalCategory = categoryRepository.findById(id);

        optionalCategory.ifPresent(category -> {
            //todo:由于前端传值逻辑错误，等前端修复后这儿还得修改
            if (Objects.equals(status, StatusConstant.ENABLE)) {
                category.setStatus(StatusConstant.ENABLE);
            } else {
                category.setStatus(StatusConstant.DISABLE);
            }

            category.setUpdateTime(LocalDateTime.now());
            category.setUpdateUser(BaseContext.getCurrentId());

            categoryRepository.saveAndFlush(category);
        });
    }

    /**
     * 根据类型查询分类
     */
    public List<Category> list(Integer type) {
        if (type == null) {
            return categoryRepository.findAllByStatus(StatusConstant.ENABLE);
        } else {
            return categoryRepository.findAllByTypeAndStatus(type, StatusConstant.ENABLE);
        }
    }


    @Override
    public String getCategoryNameById(Long id) {
        Category category = categoryRepository.findById(id).orElseThrow(() -> new EntityNotFoundException(MessageConstant.CATEGORY_NOT_FOUND));
        return category.getName();
    }
}
